#!/usr/bin/env python
# encoding: utf-8
"""
#-------------------------------------------------------------------#
#                   CONFIDENTIAL --- CUSTOM STUDIOS                 #     
#-------------------------------------------------------------------#
#                                                                   #
#                   @Project Name : Globallawonline                #
#                                                                   #
#                   @File Name    : CjFileToJg.py                      #
#                                                                   #
#                   @Programmer   : 李建                            #
#                                                                   #  
#                   @Start Date   : 2021/1/21 16:49                 #
#                                                                   #
#                   @Last Update  : 2021/1/21 16:49                 #
#                                                                   #
#-------------------------------------------------------------------#
# Classes:该类用于将web服务器上的法律文件上传到加工服务器                                                          #
#                                                                   #
#-------------------------------------------------------------------#
"""
import datetime
import os
from ftplib import FTP

from settings import FILES_DIR, FTPCONN


class CjFileToJg:
    def __init__(self):
        pass

    def ftpconnect(self, host, port, username, password):
        ftp = FTP()
        ftp.encoding = "utf-8"  # 设置ftp支持中文文件名
        ftp.connect(host, port)     # 连接的ftp server和端口
        ftp.login(username, password)   # 连接的用户名和密码
        ftp.set_pasv(False)  # 设置ftp连接为主动模式
        return ftp

    def ftpconnectun(self, host, port, username, password):
        """
        一个被动模式的ftp连接
        :param host:
        :param port:
        :param username:
        :param password:
        :return:
        """
        ftp = FTP()
        ftp.encoding = "utf-8"  # 设置ftp支持中文文件名
        ftp.connect(host, port)
        ftp.login(username, password)
        return ftp

    def __download_file(self, ftp, remotepath, localpath):
        """
        FTP文件下载
        :param remotepath: FTP服务器上的文件详细地址
        :param localpath: 本地文件的详细地址
        :return: 文件成功下载到本地或者一个错误类型
        """
        bufsize = 1024
        fp = open(localpath, 'wb')
        try:
            ftp.retrbinary('RETR ' + remotepath, fp.write, bufsize)
            ftp.set_debuglevel(0)
            fp.close()
            return True
        except Exception as e:
            print("%s：从%s服务器上下载文件失败:%s" % (str(datetime.datetime.now()),FTPCONN['host'],str(e)))
            return False

    def __upload_file(self, ftp, remotepath, localpath):
        """
        FTP文件上传
        :param remotepath: FTP服务器上的文件详细地址
        :param localpath: 本地文件的详细地址
        :return: 文件成功上传到FTP服务器或者一个错误类型
        """
        bufsize = 1024
        fp = open(localpath, 'rb')
        try:
            ftp.storbinary('STOR ' + remotepath, fp, bufsize)
            ftp.set_debuglevel(0)
            fp.close()
            return True
        except Exception as e:
            print("%s：上传文件到%s服务器失败:%s" % (str(datetime.datetime.now()),FTPCONN['host'],str(e)))
            return False

    def __export_faillaw(self, file):
        """
        重新上传上传失败的文件
        :param ftpcon: 一个ftp连接
        :param file: 上传失败目录
        :return:
        """
        ftpconn = self.ftpconnectun(FTPCONN['host'], FTPCONN['port'], FTPCONN['username'], FTPCONN['password'])
        with open(file, 'r+', encoding='utf-8') as f:  # 读取上次未上传成功的文件重新上传
            for linen in f:  # 按行读取文件
                line = linen.replace('\n', '')
                paths = line.split(', ')
                ftp_file_path = paths[0]
                path = paths[1]
                upresult = self.__upload_file(ftpconn,ftp_file_path, path)  # 上传之前上传失败的文件
                if upresult:
                    continue
                else:  # 未上传成功的继续写入上传失败记录
                    f.write(linen)
        ftpconn.quit()

    def export_law(self):
        print(str(datetime.datetime.now()) + "：开始进行法律文件自动导出")
        # self.__export_faillaw('exportfailed.txt')
        ftpconn = self.ftpconnectun(FTPCONN['host'], FTPCONN['port'], FTPCONN['username'], FTPCONN['password'])
        ftp_dirroot = ftpconn.pwd()  # 获取目标服务器的ftp原始路径
        ftpconn.quit()
        for root, dirs, files in os.walk(FILES_DIR, topdown=True):
            print("\r%s：正在导出：" % str(datetime.datetime.now())+ root)
            ftp_path = root[len(FILES_DIR) + 1:]  # 对应的服务器路径
            ftpconn = self.ftpconnectun(FTPCONN['host'], FTPCONN['port'], FTPCONN['username'], FTPCONN['password'])
            try:  # 若服务器上文件路径不存在则新建一个文件夹
                ftpconn.cwd(ftp_path)
            except:
                ftpconn.mkd(ftp_path)
            ftpconn.cwd(ftp_dirroot)  # 返回目标服务器的ftp原始工作目录
            ftp_file_list = ftpconn.nlst(ftp_path)
            ftpconn.quit()
            i = 0
            for file in files:
                i = i + 1
                path = root + '\\' + file  # 本地文件路径
                ftp_file_path = ftp_path + '/' + file  # 对应ftp服务器上的文件路径
                if ftp_file_path in ftp_file_list:
                    continue
                else:
                    ftpconn = self.ftpconnectun(FTPCONN['host'], FTPCONN['port'], FTPCONN['username'],FTPCONN['password'])
                    upresult = self.__upload_file(ftpconn, ftp_file_path, path)  # 将文件上传到ftp服务器
                    ftpconn.quit()
                    if upresult:  # 将上传失败的文件写入错误记录
                        continue
                    else:
                        # with open('exporterro.txt', 'a', encoding='utf-8') as fe:
                        #     fe.write(str(upresult) + '\n')
                        with open('exportfailed.txt', 'a', encoding='utf-8') as f:
                            f.write(ftp_file_path + ', ' + path + '\n')
        self.__export_faillaw('exportfailed.txt')
        print(str(datetime.datetime.now()) + "：法律文件自动导出结束")

